<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <h1>post请求</h1>
  <input type="text" id="iptName">
  <input type="text" id="iptAge">
  <input type="text" id="iptSex">
  <button id="btn">点击提交请求</button>
  <script>
    const namei = document.getElementById('iptName')
    const agei = document.getElementById('iptAge')
    const sexi = document.getElementById('iptSex')
    const obtn = document.getElementById('btn')

    obtn.onclick = function () {
      const name = namei.value
      const age = agei.value
      const sex = sexi.value

      // 创建ajax实例
      const xhr = new XMLHttpRequest()

      // 打开
      xhr.open('POST', '/adduser', true)

      // 因为post传参方式较多,所以需要设置请求头来告诉服务器传参方式
      xhr.setRequestHeader("Content-Type", "application/json;charset=utf-8")

      // 发送
      xhr.send(JSON.stringify({
        name: name,
        age: age,
        sex: sex
      }))

      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && (xhr.status >= 200 && xhr.status <= 299)) {
          console.log(JSON.parse(xhr.responseText));
        }
      }
    }
  </script>
</body>

</html>